import counter.CombiningTree;



public class TestCombiningTree {

    static final int numThreads = 4;
    static final int numLeaf = 4;
    static final int addTimes = 8;


    public static void main(String[] args) {
        CombiningTree combiningTree = new CombiningTree(numLeaf);

        double costTime = runTest(combiningTree);
        int result = combiningTree.getCounter();

        System.out.println("costTime = " + costTime + ", " + "result = " + result);
        
    }

    public static double runTest(CombiningTree combiningTree){
        TestCounterThread[] threads = new TestCounterThread[numThreads];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new TestCounterThread(combiningTree, addTimes);
        }

        long startTime = System.nanoTime();
        try {
            for (int i = 0; i < threads.length; i++) {
                threads[i].start();
            }

            for (int i = 0; i < threads.length; i++) {
                threads[i].join();
            }
        } catch (Exception e) {
            System.out.println("Exception" + e.getMessage());
        }

        long endTime = System.nanoTime();
        double costTime = (double)(endTime - startTime);
        costTime = costTime / 1000000.0;
        System.out.printf(costTime + ",\n");    

        return costTime;
    }
    
}


class TestCounterThread extends Thread{
    CombiningTree combiningTree;
    int addTimes;

    TestCounterThread(CombiningTree _combiningTree, int _addTimes) {
        combiningTree = _combiningTree;
        addTimes = _addTimes;
    }

    public void run() {
        for (int i = 0; i < addTimes; i++) {
            try{
                combiningTree.getAndIncrement();
            } catch (Exception ex) {
                // System.out.println("Exception: " + ex.getMessage());
            }
        }
    }

}